import { Component, OnInit, OnDestroy  } from '@angular/core';
import { ChatService } from './service/chat.service';

@Component({
  selector: 'ngx-chat',
  templateUrl: 'chat.component.html',
  styleUrls: ['chat.component.scss'],
  providers: [ ChatService ],
})
export class ChatComponent implements OnInit, OnDestroy {

  messages: any[] = [];
  connection: any;

  constructor(protected chatService: ChatService) {
  }

  sendMessage(event: any) {
    const files = !event.files ? [] : event.files.map((file) => {
      return {
        url: file.src,
        type: file.type,
        icon: 'nb-compose'
      };
    });

    const msgObj = {
      text: event.message,
      date: new Date(),
      reply: true,
      type: files.length ? 'file' : 'text',
      files: files,
      user: {
        name: 'Jonh Doe',
        avatar: 'https://i.gifer.com/no.gif'
      }
    };

    this.chatService.sendMessage(msgObj);
  }

  ngOnInit() {
    this.connection = this.chatService.getMessages()
      .subscribe(message => {
        this.messages.push(message);
      })
  }

  ngOnDestroy() {
    this.connection.unsubscribe();
  }
}
